package cn.com.header.web.controller.sys;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.net.URLEncoder;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.com.header.core.util.LangUtils;
import cn.com.header.web.model.sys.Attachment;
import cn.com.header.web.service.sys.AttachService;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * 附件管理（也包含了图片）
 * @author LinZongxue 2012-11-28
 *
 */
@Controller
@RequestMapping("sys/attach")
public class AttachController {
	@Resource private AttachService attachSvc;

	/**
	 * 上传附件
	 */
	@RequestMapping("upload")
	public @ResponseBody void upload(MultipartFile file, Attachment attach, HttpServletResponse response, HttpServletRequest request) throws IOException {
		attach.setFileName(file.getOriginalFilename());
		//由于客户端使用flash组件上传，这里获取的文件类型不正确。
		//文件类型的获取放到attachSvc.writeAndSave()方法中设置
		//attach.setFileType(file.getContentType()); //application/octet-stream
		attach.setFileSize(file.getSize());
		attachSvc.writeAndSave(attach,file.getInputStream(),request);
		//为了防止IE提示下载，不能直接返回attach对象，而应该以html的形式输出json字符串
		}

	/**
	 * 下载附件
	 */
	@RequestMapping("download")
	public void download(Long id, Model model, HttpServletResponse response,HttpServletRequest request){
		if (id == null) return;
		Attachment attach = attachSvc.loadAttach(id);
		try{
			response.setContentType("application/octet-stream");
			response.addHeader("Content-Disposition", "attachment;filename=" +
					new String((attach.getFileName()).getBytes("GB2312"),"iso8859-1"));
			InputStream input = attachSvc.getFileInputStream(id,request);
			IOUtils.copy(input, response.getOutputStream());
			input.close();
			response.flushBuffer();
			response.getOutputStream().close();
		} catch (Exception e){
			e.printStackTrace();
		/*	this.outputHtml("下载附件发生意外，请返回", response);
			AppUtils.logError("下载附件出错：%s", e.getMessage());*/
		}
	}

	/**
	 * 打开显示图片文件
	 */
	@RequestMapping("view-image")
	public void viewImage(Long id, String c, HttpServletResponse response,HttpServletRequest request){
		response.setContentType("image/jpeg");
		if (id == null) return;
		if (!codeMatches(id, c)){
			/*logger.debug("查看图片时验证码有误：{}", c);*/
			return;
		}
		Attachment attach = attachSvc.loadAttach(id);
		if (attach == null) return;
		if (StringUtils.contains(attach.getFileType(), "image")){
			response.setContentType(attach.getFileType());
		}
		try{
			InputStream input = attachSvc.getFileInputStream(id,request);
			IOUtils.copy(input, response.getOutputStream());
			input.close();
			response.getOutputStream().close();
		}
		catch (Exception e){
			response.reset();
		}
	}
	private boolean codeMatches(Long imgId, String code){
		if (imgId == null || code == null) return false;
		String tmp = BigInteger.valueOf(imgId).multiply(BigInteger.valueOf(imgId % 10)).toString();//imgId*(imgId%10)
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < tmp.length(); i ++){
			int c = LangUtils.parseInt(tmp.substring(i, i + 1));
			sb.append(c * (c + 1));
		}
		if (sb.length() > 8) sb.delete(0, sb.length() - 8);
		return sb.toString().equals(code);
	}
}
